package com.huirui.server.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huirui.server.mapper.SearchLogMapper;
import com.huirui.server.pojo.dto.ProductSearchDto;
import com.huirui.server.pojo.entity.SearchLog;
import com.huirui.server.pojo.result.PageResult;
import com.huirui.server.pojo.vo.ProductBriefInfoVo;
import com.huirui.server.pojo.vo.SearchLogVo;
import com.huirui.server.service.ProductService;
import com.huirui.server.service.SearchLogService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yujun
 * @description 针对表【t_user_search_log(用户搜索记录表（存储所有搜索关键词，含未匹配商品的记录）)】的数据库操作Service实现
 * @createDate 2025-09-16 12:11:45
 */
@Service
@Slf4j
public class SearchLogServiceImpl extends ServiceImpl<SearchLogMapper, SearchLog>
        implements SearchLogService {

    @Resource
    private ProductService productService;

    @Override
    public List<SearchLogVo> listTopSearches() {
        LocalDateTime oneMonthAgo = LocalDateTime.now().minusDays(30);
        List<SearchLog> searchLogList = lambdaQuery()
                .select(SearchLog::getId, SearchLog::getKeyword)
                .orderByDesc(SearchLog::getCount)
                .ge(SearchLog::getSearchTime, oneMonthAgo)
                .last("LIMIT 10")
                .list();
        return searchLogList
                .stream()
                .map(searchLog
                        -> SearchLogVo
                        .builder()
                        .id(searchLog.getId())
                        .keyword(searchLog.getKeyword())
                        .build()
                ).toList();
    }

    @Override
    public PageResult<ProductBriefInfoVo> listProductsByComprehensive(ProductSearchDto productSearchDto) {
        String keyword = productSearchDto.getKeyword();
        Long page = productSearchDto.getPage();
        Long pageSize = productSearchDto.getPageSize();
        Page<ProductBriefInfoVo> pageParam = new Page<>(page, pageSize);
        IPage<ProductBriefInfoVo> res = productService.listProductsByComprehensive(keyword, pageParam);
        res.getRecords().forEach(productBriefInfoVo -> {
            if (productBriefInfoVo.getTags() == null) {
                productBriefInfoVo.setTags(new ArrayList<>());
            }
            if (isWithin30Days(productBriefInfoVo.getCreateTime())) {
                productBriefInfoVo.getTags().add("新品上市");
            }
            if (productBriefInfoVo.getDiscountPrice() < productBriefInfoVo.getOriginalPrice()) {
                productBriefInfoVo.getTags().add("限时特价");
            }
        });
        return PageResult.from(res);
    }

    /**
     * 判断目标时间是否在距离当前时间的30天之内（含30天前和当前时间）
     *
     * @param targetTime 待判断的LocalDateTime对象
     * @return 若在30天内返回true，否则返回false（目标时间为null时返回false）
     */
    public static boolean isWithin30Days(LocalDateTime targetTime) {
        // 处理目标时间为null的情况
        if (targetTime == null) {
            return false;
        }

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 计算30天前的时间
        LocalDateTime thirtyDaysAgo = now.minusDays(30);

        // 判断：目标时间不早于30天前，且不晚于当前时间
        return !targetTime.isBefore(thirtyDaysAgo) && !targetTime.isAfter(now);
    }


    @Override
    public PageResult<ProductBriefInfoVo> listProductsBySales(ProductSearchDto productSearchDto) {
        String keyword = productSearchDto.getKeyword();
        Long page = productSearchDto.getPage();
        Long pageSize = productSearchDto.getPageSize();
        Page<ProductBriefInfoVo> pageParam = new Page<>(page, pageSize);
        IPage<ProductBriefInfoVo> res = productService.listProductsBySales(keyword, pageParam);
        res.getRecords().forEach(productBriefInfoVo -> {
            if (productBriefInfoVo.getTags() == null) {
                productBriefInfoVo.setTags(new ArrayList<>());
            }
            if (isWithin30Days(productBriefInfoVo.getCreateTime())) {
                productBriefInfoVo.getTags().add("新品上市");
            }
            if (productBriefInfoVo.getDiscountPrice() < productBriefInfoVo.getOriginalPrice()) {
                productBriefInfoVo.getTags().add("限时特价");
            }
        });
        return PageResult.from(res);
    }

    @Override
    public PageResult<ProductBriefInfoVo> listProductsByPrice(ProductSearchDto productSearchDto) {
        String orderBy = productSearchDto.getOrderBy();
        String keyword = productSearchDto.getKeyword();
        Long page = productSearchDto.getPage();
        Long pageSize = productSearchDto.getPageSize();
        Page<ProductBriefInfoVo> pageParam = new Page<>(page, pageSize);
        IPage<ProductBriefInfoVo> res = productService.listProductsByPrice(keyword, orderBy, pageParam);
        res.getRecords().forEach(productBriefInfoVo -> {
            if (productBriefInfoVo.getTags() == null) {
                productBriefInfoVo.setTags(new ArrayList<>());
            }
            if (isWithin30Days(productBriefInfoVo.getCreateTime())) {
                productBriefInfoVo.getTags().add("新品上市");
            }
            if (productBriefInfoVo.getDiscountPrice() < productBriefInfoVo.getOriginalPrice()) {
                productBriefInfoVo.getTags().add("限时特价");
            }
        });
        return PageResult.from(res);


    }

    @Override
    public PageResult<ProductBriefInfoVo> listProductsByTime(ProductSearchDto productSearchDto) {
        String keyword = productSearchDto.getKeyword();
        Long page = productSearchDto.getPage();
        Long pageSize = productSearchDto.getPageSize();
        Page<ProductBriefInfoVo> pageParam = new Page<>(page, pageSize);
        IPage<ProductBriefInfoVo> res = productService.listProductsByTime(keyword, pageParam);
        res.getRecords().forEach(productBriefInfoVo -> {
            if (productBriefInfoVo.getTags() == null) {
                productBriefInfoVo.setTags(new ArrayList<>());
            }
            if (isWithin30Days(productBriefInfoVo.getCreateTime())) {
                productBriefInfoVo.getTags().add("新品上市");
            }
            if (productBriefInfoVo.getDiscountPrice() < productBriefInfoVo.getOriginalPrice()) {
                productBriefInfoVo.getTags().add("限时特价");
            }
        });
        return PageResult.from(res);
    }


}




